#pyjwt加密算法
from functools import wraps
import jwt
import time
from jwt import ExpiredSignatureError, InvalidTokenError

from flask import current_app,request

#生成token
def generate_token(data):
    #设置数据的过期时间
    data.update({'exp': int(time.time()) + current_app.config['JWT_EXPIRATION_DELTA']})

    #数据的加密
    token = jwt.encode(data,current_app.config['SECRET_KEY'],algorithm='HS256')
    return token

#解析token
def verify_token(token):
    try:
        data = jwt.decode(token, current_app.config['SECRET_KEY'], algorithms=['HS256'],options={'verify_exp': True})
        return data
    except ExpiredSignatureError:
        # token 已过期
        return None
    except InvalidTokenError:
        # token 无效
        return None
    except Exception:
        # 其他错误
        return None

def login_required(view_func):
    @wraps(view_func)
    def verify_token_info(*args,**kwargs):
        #获取用户传递过来的token
        token = request.headers.get('token')
        #解析token
        if verify_token(token):
            return view_func(*args,**kwargs)
        else:
            return {'status':401,'msg':'token无效，请登录'}
    return verify_token_info

